package com.jymj.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;

/**
 * Created by ljj on 2018/12/17.
 */
public class UpOrDownFile {

    private static final Logger LOGGER = LoggerFactory.getLogger(UpOrDownFile.class);

    public static R upload(HttpServletRequest request, String saveDir) {
        //返回地址
        String SAVE_filr_DIR = null;
        //文件名称
        String fileName = null;
        // 获取 web application的绝对路径
        String appPath = request.getServletContext().getRealPath("");
        // 构造文件存放的路径
        String savePath = appPath + File.separator + saveDir;
        // 如果文件存放路径不存在，则mkdir一个
        File fileSaveDir = new File(savePath);
        if (!fileSaveDir.exists()) {
            fileSaveDir.mkdirs();
        }
        //转换成多部分request
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        //取得request中的所有文件名
        Iterator<String> iter = multiRequest.getFileNames();
        while (iter.hasNext()) {
            //取得上传文件
            MultipartFile file = multiRequest.getFile(iter.next());
            if (file != null) {
                //取得当前上传文件的文件名称
                String myFileName = file.getOriginalFilename();
                //如果名称不为“”,说明该文件存在，否则说明该文件不存在
                if (!"".equals(myFileName.trim())) {
                    fileName = file.getOriginalFilename();//"demoUpload" + file.getOriginalFilename();
                    // 如果文件存放路径不存在，则mkdir一个
                    File file_SaveDir = new File(savePath);
                    if (!file_SaveDir.exists()) {
                        file_SaveDir.mkdir();
                    }
                    String ext = fileName.substring(fileName.indexOf("."));
                    TimeString st = new TimeString();
                    String aa = st.getTimeString();
                    SAVE_filr_DIR = saveDir + File.separator + aa + ext;//数据库存放地址
                    File localFile = new File(savePath + File.separator + aa + ext);//实际存放地址
                    try {
                        file.transferTo(localFile);
                    } catch (IOException e) {
                        LOGGER.error(e.getMessage(), e);
                        return R.error();
                    }
                }
            }
        }
        return R.ok().put("savePath", SAVE_filr_DIR).put("filename", fileName);
    }

    public static void download() {

    }
}
